package report_service

import (
	"fmt"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/errors"
	"peilian-api/app/model"
	"peilian-api/utils/sdk"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type SessionService struct{}

func (s *SessionService) JudgeSessionFirst(ctx *gin.Context) (bool, *errors.ErrRes) {
	uid, exists := ctx.Get("uid")
	if !exists {
		return false, errors.NewErrInfo(errors.SessionUidErrorCode, fmt.Errorf("该用户未登录"))
	}
	count, _ := new(tables.Session).FindSessionCountByUid(uid.(uint))
	if count <= 1 {
		return true, nil
	}
	return false, nil
}

func (s *SessionService) SessionSatisfied(ctx *gin.Context, sfs model.SatisfiedScore) (int64, *errors.ErrRes) {
	uid, exists := ctx.Get("uid")
	if !exists {
		return 0, errors.NewErrInfo(errors.SessionUidErrorCode, fmt.Errorf("该用户未登录"))
	}

	vpData := new(tables.Vpdata)
	vpData.Type = tables.SATISFIED_TYPE
	vpData.UserId = uid.(uint)
	vpData.Info = strconv.Itoa(int(sfs.Score))
	id, err := vpData.InsertVp(*vpData)
	if err != nil {
		return 0, errors.NewErrInfo(10001, fmt.Errorf("打分失败"))
	}
	return id, nil
}

// 判断5分钟内报告未生成
func (s *SessionService) JudgeReport(ctx *gin.Context) {
	sessions, _ := new(tables.Session).FindReportsByWhereStr("url = '' and status <> 1 and finish_at != '0000-00-00 00:00:00.000'")
	for _, v := range sessions {
		exTime := time.Now().Unix() - v.FinishAt.Unix()
		if exTime < 300 {
			continue
		}
		GenerateReport(ctx, strconv.Itoa(int(v.ID)), true)
		sdk.SendMsg(fmt.Sprintf("第%d场,5分钟内未生成报告,已自动处理", v.ID))
	}
}
